/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.apt.ServletClient;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apt.connectDB.MyConnect;
import org.apt.Bean.MemberEnties;
import org.apt.connectDB.MahoaPassword;
import com.myapp.DAO.MemberDao;
import org.apt.connectDB.Mail;

/**
 *
 * @author Administrator
 */
public class registerMember extends HttpServlet {

    /**
     * function  register member
     * @param member
     * @return true if register success else return false
     */
    public boolean Register(MemberEnties member) {
        //insert db
        Connection conn = null;
        PreparedStatement ps = null;
        boolean resuilt = false;
        MahoaPassword mahoa = new MahoaPassword();
        try {
            if (MemberDao.checkExistUser(member.getTxtUserName())) {
                resuilt = false;
            } else {
                String password = MahoaPassword.MD5Password(member.getTxtPassword());
                conn = MyConnect.getConnection();
                String sql = "insert into  Member ( UserName , Password ,FullName ,Image , Email ,  DOB ,IDCard ,MobilePhone ,HomePhone ,Address ,Status , Description , Gender) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                ps = conn.prepareCall(sql);
                ps.setString(1, member.getTxtUserName());
                ps.setString(2, password);
                ps.setString(3, member.getTxtFullName());
                ps.setString(4, member.getTxtImage());
                ps.setString(5, member.getTxtEmail());
                ps.setString(6, member.getTxtBirthday());
                ps.setString(7, member.getTxtIDCard());
                ps.setString(8, member.getTxtMobile());
                ps.setString(9, member.getTxtHomePhone());
                ps.setString(10, member.getTxtAddress());
                ps.setBoolean(11, true);
                ps.setString(12, "");
                ps.setBoolean(13, member.isTxtgender());
                int i = ps.executeUpdate();
                if (i > 0) {
                    resuilt = true;
                } else {
                    resuilt = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resuilt;
    }

    /**
     * process request from client
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws FileUploadException
     * @throws Exception
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        MemberEnties mber;

        String random = MahoaPassword.getRandomString(20);
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        Hashtable params = new Hashtable();
        String filename = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {
                try {
                    String itemName = item.getName();
                    filename = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String realPath = getServletContext().getRealPath("/") + "images/imagemember\\" + random + "-" + filename;
                    File saveFile = new File(realPath);
                    item.write(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean gender;
                String username = (String) params.get("txtUserName");
                String password = (String) params.get("txtPassword");
                String fullname = (String) params.get("txtFullName");
                String value = (String) params.get("gender");
                if (value.equals("1")) {
                    gender = true;
                } else {
                    gender = false;
                }
                String birthday = (String) params.get("txtBirthday");
                String idcard = (String) params.get("txtIDCard");
                String email = (String) params.get("txtEmail");
                String mobile = (String) params.get("txtMobile");
                String homephone = (String) params.get("txtHomePhone");
                String address = (String) params.get("txtAddress");
                String image = random + "-" + filename;

                boolean userexit = MemberDao.checkExistUser(username);
                if (userexit) {
                    out.print("<script>alert('The user name is existed please choise a difference user name !');window.location.href='Register.jsp';</script>");
                } else {
                    mber = new MemberEnties(username, password, fullname, image, email, birthday, idcard, mobile, homephone, address, true, "", gender);
                    if (Register(mber)) {
                        //send mail to member
                        String subject = "Admin National level paper!";
                        String body = "Configuration your account has been success! \nYour user name: " + username + " \nPassword: " + password + "\nThank you!\n\n\nNational Level Paper Presentation-Group 183";
                        Mail.sendMail(email, subject, body);
                        // create session member
                        HttpSession session = request.getSession(true);
                        session.setAttribute("member", mber);
                        out.print("<script>alert('Registration success, we have send a email to email address, plese check email!');window.location.href='index.jsp';</script>");
                    } else {
                        out.print("<script>alert('Registration fail!');window.location.href='error.jsp';</script>");
                    }
                    try {
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        System.out.println("Error:" + ex.getMessage() + "");
                    } finally {
                        out.close();
                    }
                }
            }
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(registerMember.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(registerMember.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(registerMember.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(registerMember.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
